package com.fingard.dsp.bank.directbank.citic01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class CITIC01BatPayRec extends CITIC01Base implements IBatPayRec {
    //1988
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    //9188
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return d_BatPayRec(p_req9188);
    }

    //批量代收和批量代付提交
    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
        //返回ATS的对象
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        try {
            CITIC01Header tmpBnkHeader = new CITIC01Header();
            //DLSALIMP:代发工资   DLOTHSUB:代发   DLAGENTF:代扣
            //198802 代发工资
            if (p_reqBat.reqHeader.transType.equals("1988")) {
                if (p_reqBat.reqHeader.commandCode.equals("198802")) {
                    tmpBnkHeader.action = "DLSALIMP";
                } else if (p_reqBat.reqHeader.commandCode.equals("198808")) {
                    tmpBnkHeader.action = "DLUPRSUB";
                } else {
                    tmpBnkHeader.action = "DLOTHSUB";
                }
            } else if (p_reqBat.reqHeader.transType.equals("9188")) {
                tmpBnkHeader.action = "DLAGENTF";
            }
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter, tmpBnkHeader);
            xmlWriter.writeElementString("clientID", p_reqBat.reqBatchNO);
            xmlWriter.writeElementString("totalNumber", p_reqBat.totalNum);
            xmlWriter.writeElementString("totalAmount", p_reqBat.totalAmt);
            if (p_reqBat.reqHeader.transType.equals("1988")) {
                xmlWriter.writeElementString("payAccountNo", p_reqBat.ownAct);
            } else if (p_reqBat.reqHeader.transType.equals("9188")) {
                xmlWriter.writeElementString("rcvAccountNo", p_reqBat.ownAct);
            }
            String memo = p_reqBat.useType;
            if (memo.length() > 20) {
                memo = memo.substring(0, 21);
            }
            memo = memo + "#" + p_reqBat.abstractATS;
            if (tmpBnkHeader.action.equals("DLSALIMP")) {//工资
                xmlWriter.writeElementString("abstract", memo);
            }
            xmlWriter.writeElementString("preFlg", "0");
            xmlWriter.writeElementClosed("preDate");
            xmlWriter.writeElementClosed("preTime");
            if (!tmpBnkHeader.action.equals("DLSALIMP")) {//非工资
                xmlWriter.writeElementString("memo", memo);
            } else {//<yearMonth></yearMonth><!--代发年月char(6) 格式YYYYMM-->
                xmlWriter.writeElementString("yearMonth", Format.Date6YearMonth.format(p_reqBat.getPayDateTime()));
            }
            xmlWriter.writeStartElementByAttr("list", "<list name=\"userDataList\">");
            //需要进行对账码拼接以及节点解析，采用XElement进行处理
            int seqNo = 0;
            while (p_reqBat.readRecord()) {
                XElement tmpXElement = new XElement("row", "");

                if (p_reqBat.reqHeader.transType.equals("1988") && tmpBnkHeader.action.equals("DLSALIMP")) {//工资
                    tmpXElement.addChild(new XElement("employeeNo", p_reqBat.readedDetail.askNumber));
                    tmpXElement.addChild(new XElement("employeeName", p_reqBat.readedDetail.recName));
                    tmpXElement.addChild(new XElement("recAccountNo", p_reqBat.readedDetail.recAct));
                    tmpXElement.addChild(new XElement("tranAmount", p_reqBat.readedDetail.payAmount));
                } else {
                    if (p_reqBat.reqHeader.transType.equals("1988")) {
                        if ("DLUPRSUB".equals(tmpBnkHeader.action)) {
                            tmpXElement.addChild(new XElement("ID", String.format("%5s", seqNo++).replace(' ', '0')));
                            tmpXElement.addChild(new XElement("field1", p_reqBat.readedDetail.askNumber));
                        }
                        tmpXElement.addChild(new XElement("recAccountNo", p_reqBat.readedDetail.recAct));
                        tmpXElement.addChild(new XElement("recAccountName", p_reqBat.readedDetail.recName));
                    } else if (p_reqBat.reqHeader.transType.equals("9188")) {
                        tmpXElement.addChild(new XElement("payAccountNo", p_reqBat.readedDetail.payAct));
                        tmpXElement.addChild(new XElement("payAccountName", p_reqBat.readedDetail.payName));
                    }
                    tmpXElement.addChild(new XElement("tranAmount", p_reqBat.readedDetail.payAmount));
                    tmpXElement.addChild(new XElement("abstract", p_reqBat.readedDetail.askNumber));
                }

                xmlWriter.writeXElement(tmpXElement);
            }
            xmlWriter.writeEndDocument();//写入报文完成
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    retAts.respCode = "0";
                    retAts.respInfo = tmpBkReader.getFirstText("/stream/statusText");
                    retAts.reqSeqID = p_reqBat.reqBatchNO;
                    retAts.transState = tmpBkReader.getFirstText("/stream/status");
                    retAts.payInfoCode = retAts.transState;
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                retAts.respCode = "0";
                retAts.respInfo = tmpStrRet[1];
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = tmpStrRet[0];
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }

        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            e.printStackTrace();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_reqBat.reqBatchNO;
        }
        retAts.writeRetToATS();
        return retAts;
    }

    //1998 状态查询
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return d_QryBatPayRec(p_req1998);
    }

    //9198
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return d_QryBatPayRec(p_req9198);
    }

    //批量代收和批量代付状态查询
    public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
        //返回ATS的对象
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        retAts.respCode = "";
        CITIC01Header tmpBnkHeader = new CITIC01Header();
        /*
        //DLSALIMP:代发工资   DLOTHSUB:代发   DLAGENTF:代扣
		//198802 代发工资
		if(p_reqQryBat.reqHeader.transType.equals("1998")){
			if(p_reqQryBat.reqHeader.commandCode.equals("198802")){
				tmpBnkHeader.action = "DLSALCOL";
			}
			else{
				tmpBnkHeader.action = "DLOTHCOL";
			}
		}
		else if(p_reqQryBat.reqHeader.transType.equals("9188")){
			tmpBnkHeader.action = "DLAGECOL";
		}
		XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
		writeCommonHeader(xmlWriter, tmpBnkHeader);//写入通用的头部节点
		xmlWriter.writeElementString("startDate", Format.Date8Format.format(p_reqQryBat.getBgnDateTime()));
		xmlWriter.writeElementString("endDate", Format.Date8Format.format(new Date()));	
		xmlWriter.writeEndDocument();
		boolean isFinished = false;
		String tmpREQNBR = "";
		String tmpStrBatchREQSTA = "";
		String tmpStrBatchRTNFLG = "";
		try{
			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
			if(tmpStrRet[0].length() == 0){
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
				if(tmpBkReader != null){
					String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
					String tmpRetMsg = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
					if(tmpRetCode != null && tmpRetCode.equals("0")){
						int tmpCountQYZ = tmpBkReader.countElement("/CMBSDKPGK/NTQATSQYZ");
						if(tmpCountQYZ == 1){
							//String tmpStrC_RTNFLG = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/C_RTNFLG");
                            String tmpStrC_REQSTA = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/C_REQSTA");
                            String tmpStrREQSTA = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/REQSTA");//业务请求状态
                            //业务处理结果//当REQSTA=FIN且RTNFLG=S需检查RSV62Z第一位是否为’P’，是表示部分成功，否则表示全部成功。
                            String tmpStrRTNFLG = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/RTNFLG");
                            String tmpStrSUCAMT = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/SUCAMT");
                            String tmpStrSUCNUM = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/SUCNUM");
                            String tmpStrERRDSP = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/ERRDSP");
                            String tmpStrYURREF = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/YURREF");
                            tmpREQNBR = tmpBkReader.getFirstText("/CMBSDKPGK/NTQATSQYZ/REQNBR");
                            if (tmpStrYURREF != null && p_reqQryBat.reqBatchNO.equals(tmpStrYURREF)){
                            	tmpStrBatchREQSTA = tmpStrREQSTA;
                            	tmpStrBatchRTNFLG = tmpStrRTNFLG;
                                retAts.reqSeqID = tmpStrYURREF;
                                if (tmpStrERRDSP != null && tmpStrERRDSP.length() > 32)
                                {
                                    tmpStrERRDSP = tmpStrERRDSP.substring(0, 33);
                                }
                                if (tmpStrREQSTA.equals("FIN") && tmpStrRTNFLG.equals("F") && StringHelper.isNullOrEmpty(tmpREQNBR))
                                {
                                	float tmpSUCAMT = Float.parseFloat(tmpStrSUCAMT);
                                	float tmpSUCNUM = Float.parseFloat(tmpStrSUCNUM);
                                	//tmpStrSUCAMT.equals("0.00") && tmpStrSUCNUM.equals("00000")
                                	//查明细
                                    //AGN0025 无一笔入帐成功 查明细
                                    //if (!tmpStrERRDSP.startsWith("AGN0025"))
                                    //{
                                    //}
                                	if (tmpSUCAMT==0 && tmpSUCNUM==0)
                                    {
                                    	retAts.respCode = "0";
                                    	retAts.respInfo = tmpStrERRDSP;
                                    	retAts.transState = tmpStrREQSTA + "+" + tmpStrRTNFLG;
                                    	retAts.payInfoCode = tmpStrERRDSP;
                                    	isFinished = true;
                                    }
                                	else{
                                		retAts.respCode = "-1";
            							retAts.respInfo = "成功笔数或成功金额不符合预期";
                                	}
                                }
                                else if (tmpStrREQSTA != null && !tmpStrREQSTA.equals("FIN"))
                                {
                                    
                                	retAts.respCode = "0";
                                	retAts.respInfo = tmpStrC_REQSTA;
                                	retAts.transState = tmpStrREQSTA;
                                	retAts.payInfoCode = tmpStrREQSTA;
                                    isFinished = true;
                                }
                                else if(StringHelper.isNullOrEmpty(tmpStrREQSTA)){
                                	retAts.respCode = "-1";
                                	retAts.respInfo = "批次的业务请求状态为空";
                                }
                            }
                            else{
                            	retAts.respCode = "-1";
                            	retAts.respInfo = "招行批号"+tmpStrYURREF+"与请求批号"+p_reqQryBat.reqBatchNO+"不相符";
                            }
						}
						else if(tmpCountQYZ == 0){
							boolean tmpReadRoot = tmpBkReader.read("/CMBSDKPGK");
							int tmpCountChild = -1;
							if(tmpReadRoot){
								tmpCountChild = tmpBkReader.readedXElement.countChildren();
							}
							if (tmpRetCode.equals("0") && tmpStrRet[1].indexOf("NTQATSQYZ") < 0 && tmpReadRoot && tmpCountChild==1)
                            {
								retAts.respCode = "0"; 
                                retAts.respInfo = "招行不存在该业务参考号";
                                retAts.transState = PaymentState.FAIL_Batch;
                                retAts.reqSeqID = p_reqQryBat.reqBatchNO;                                
                                retAts.payInfoCode = "E1302";
                                isFinished = true;
                            }
                            else
                            {
                            	retAts.respCode = "-1";
    							retAts.respInfo = "招行返回报文不符合预期";
                            }
						}
						else{
							retAts.respCode = "-1";
							retAts.respInfo = "招行返回多个批次NTQATSQYZ节点";
						}
					}
					else{
						retAts.respCode = "-1";
						retAts.respInfo = tmpRetMsg;
					}
				}
				else{
					retAts.respCode = "-1";
					retAts.respInfo = tmpSbMsg.toString();
				}
			}
			else{
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}
		}
		catch (Exception e) {
			retAts.respCode = "-1";
			retAts.respInfo = e.getMessage();
			e.printStackTrace();
		}
		
		if(isFinished || retAts.respCode.equals("-1")){
			if(retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)){
				retAts.reqSeqID = p_reqQryBat.reqBatchNO;
			}
			retAts.writeBeforeDetail();
			retAts.writeAfterDetail();
			return retAts;
		}
		*/
        //查明细
        if (p_reqQryBat.reqHeader.transType.equals("1998")) {
            if (p_reqQryBat.reqHeader.commandCode.equals("198802")) {
                //tmpBnkHeader.action = "DLSALDET";
                return d_QryBatPayRec_198802(p_reqQryBat);
            } else if (p_reqQryBat.reqHeader.commandCode.equals("198808")) {
                tmpBnkHeader.action = "DLUPRDET";
            } else {
                tmpBnkHeader.action = "DLOTHDET";
            }
        } else if (p_reqQryBat.reqHeader.transType.equals("9198")) {
            tmpBnkHeader.action = "DLAGEDET";
        }
        XmlTextWriter xmlWriter = null;
        xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonHeader(xmlWriter, tmpBnkHeader);//写入通用的头部节点
        xmlWriter.writeElementString("clientID", p_reqQryBat.reqBatchNO);
        xmlWriter.writeEndDocument();
        try {
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpStatus = tmpBkReader.getFirstText("/stream/status");
                    String tmpStatusText = tmpBkReader.getFirstText("/stream/statusText");
                    if (tmpStatus != null && tmpStatus.length() > 0) {
                        retAts.respCode = "0";
                        retAts.reqSeqID = p_reqQryBat.reqBatchNO;
                        int tmpCountRow = tmpBkReader.countElement("/stream/list/row");
                        if (tmpCountRow > 0 && isActiveRetCode(tmpStatus)) {
                            retAts.writeBeforeDetail();
                            while (tmpBkReader.read("/stream/list/row")) {
                                RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                if (p_reqQryBat.reqHeader.transType.equals("1998")) {
                                    tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleText("recAccountNo");
                                    tmpRetDetail.recName = tmpBkReader.readedXElement.getSingleText("recAccountName");
                                } else if (p_reqQryBat.reqHeader.transType.equals("9198")) {
                                    tmpRetDetail.payAct = tmpBkReader.readedXElement.getSingleText("payAccountNo");
                                    tmpRetDetail.payName = tmpBkReader.readedXElement.getSingleText("payAccountName");
                                }
                                tmpRetDetail.payAmount = tmpBkReader.readedXElement.getSingleText("tranAmount");
                                tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleText("abstract");
                                tmpRetDetail.result = tmpBkReader.readedXElement.getSingleText("status");
                                tmpRetDetail.memo = tmpBkReader.readedXElement.getSingleText("statusText");
                                tmpRetDetail.payInfoCode = tmpRetDetail.result;

                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        } else if (tmpCountRow == 0) {
                            retAts.transState = tmpStatus + "+" + tmpStatusText;
                            retAts.respInfo = tmpStatusText;
                            retAts.payInfoCode = tmpStatus;
                            retAts.writeBeforeDetail();
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = tmpStatusText;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpStatusText;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_reqQryBat.reqBatchNO;
        }
        if (retAts.respCode.equals("-1")) {
            retAts.writeBeforeDetail();
        }
        retAts.writeAfterDetail();
        return retAts;
    }

    public RetAtsQryBatPayRec d_QryBatPayRec_198802(ReqQryBatPayRec p_reqQryBat) throws Exception {
        //返回ATS的对象
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        retAts.respCode = "";
        CITIC01Header tmpBnkHeader = new CITIC01Header();
        tmpBnkHeader.action = "DLSALDET";
        int startRecord = 1;
        int totalRecords = 2;
        while (startRecord < totalRecords) {
            XmlTextWriter xmlWriter = null;
            xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter, tmpBnkHeader);//写入通用的头部节点
            xmlWriter.writeElementString("clientID", p_reqQryBat.reqBatchNO);
            xmlWriter.writeElementString("pageNumber", "20");
            xmlWriter.writeElementString("startRecord", String.valueOf(startRecord));

            xmlWriter.writeEndDocument();
            try {
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpStatus = tmpBkReader.getFirstText("/stream/status");
                        String tmpStatusText = tmpBkReader.getFirstText("/stream/statusText");
                        totalRecords = Integer.parseInt(tmpBkReader.getFirstText("/stream/totalRecords"));
                        if (tmpStatus != null && tmpStatus.length() > 0) {
                            retAts.respCode = "0";
                            retAts.reqSeqID = p_reqQryBat.reqBatchNO;
                            int tmpCountRow = tmpBkReader.countElement("/stream/list/row");
                            startRecord += tmpCountRow;
                            if (tmpCountRow > 0 && isActiveRetCode(tmpStatus)) {
                                retAts.writeBeforeDetail();
                                while (tmpBkReader.read("/stream/list/row")) {
                                    RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                    tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleText("recAccountNo");
                                    tmpRetDetail.recName = tmpBkReader.readedXElement.getSingleText("employeeName");
                                    tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleText("employeeNo");
                                    tmpRetDetail.result = tmpBkReader.readedXElement.getSingleText("status");
                                    tmpRetDetail.memo = tmpBkReader.readedXElement.getSingleText("statusText");
                                    tmpRetDetail.payInfoCode = tmpRetDetail.result;

                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            } else if (tmpCountRow == 0) {
                                retAts.transState = tmpStatus + "+" + tmpStatusText;
                                retAts.respInfo = tmpStatusText;
                                retAts.payInfoCode = tmpStatus;
                                retAts.writeBeforeDetail();
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = tmpStatusText;
                                break;
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = tmpStatusText;
                            break;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpStrRet[1];
                    break;
                }
            } catch (Exception e) {
                retAts.respCode = "-1";
                retAts.respInfo = e.getMessage();
                e.printStackTrace();
            }
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_reqQryBat.reqBatchNO;
        }
        if (retAts.respCode.equals("-1")) {
            retAts.writeBeforeDetail();
        }
        retAts.writeAfterDetail();
        return retAts;
    }
}
